// 条件指令Mixin
import cloneDeep from 'lodash/cloneDeep'
import { customAlphabet } from 'nanoid'
import { processingConstant } from '@ve/utils/utils'

export default {
  created() {
    this.locationPageId = this.$store.getters['preview/getNowPageId']
    if (this.info.logicInstruction && this.info.logicInstruction.length) {
      this.pageModulesStatesFlag = this.$store.getters['pageModulesState/getPageModulesStatesFlag'](this.locationPageId)
      this.pageModulesStates = this.$store.state.pageModulesState.pageModulesStates
    }
    // this.initLogicInstruction()
  },
  data() {
    return {
      pageModulesStates: {},
      pageModulesStatesFlag: {},
      locationPageId: '', // 组件所在页面ID
      conditionProperty: {
        disabled: false,
        hidden: false,
      },
    }
  },
  computed: {
    pageModulesState() {
      return this.pageModulesStates[this.locationPageId]
    },
    getHasPreview() {
      return this.$store.getters['preview/getHasPreview']
    },
  },
  watch: {
    pageModulesStatesFlag: {
      deep: true,
      handler() {
        // console.log('触发了组件条件判断值改变 》》》》》》》》》》》》》》》》》》》', newVal)
        // if (newVal === oldVal) return
        // 如果当前页面是组件所在页面 则触发条件判断函数
        // console.log(this.locationPageId === this.$store.getters['preview/getNowPageId'])
        if (this.locationPageId === this.$store.getters['preview/getNowPageId']) {
          this.initLogicInstruction()
        }
      },
    },
  },
  methods: {
    initLogicInstruction() {
      // console.log('开始执行条件判断！！')
      // 编辑模式不运行条件指令
      if (!this.getHasPreview) {
        return
      }
      // 解析组件的条件列表 计算相应属性
      this.info.logicInstruction.forEach((item) => {
        // 当有条件列表的时候才执行条件判断语句
        if (item.conditionList.length) {
          this.conditionProperty[item.dependencyProperty] = this.calculateCondition(item.conditionList)
          // console.log('this.conditionProperty ----------- ', this.conditionProperty)
        }
      })
    },
    calculateCondition(conditionList) {
      let componentId = (num) => {
        const nanoid = customAlphabet('abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMN', num)
        return nanoid()
      }
      let conditionStr = ''
      window.cacheObj = {}
      // 计算条件是否满足
      conditionList.forEach((item, index) => {
        // 先找到当前条件对应的组件
        // const matchModule = this.pageModulesState.filter((moduleItem) => item.condition.module === moduleItem.id)[0]
        const matchModule = this.$store.getters['pageModulesState/getPageModulesStates'](this.locationPageId).filter(
          (moduleItem) => item.condition.module === moduleItem.id
        )[0]
        // console.log('matchModule', matchModule)
        // 如果没有找到相应的组件 则不进行计算
        if (!matchModule) return
        const b = componentId(6)
        const d = componentId(6)
        if (item.condition.type === 'value' || item.condition.type === 'valueLength') {
          window.cacheObj[b] = matchModule.value
        } else {
          window.cacheObj[b] = matchModule.status
        }
        window.cacheObj[d] = processingConstant(this, item.condition.val)
        if (index) {
          // 从第二个条件开始 拼接条件的连接类型
          if (item.condition.type === 'value') {
            // 如果判断的是值，则直接对值进行判断
            conditionStr += ` ${item.connectType} cacheObj.${b} ${item.condition.state} cacheObj.${d}`
          } else if (item.condition.type === 'valueLength') {
            // 如果判断的是值长度 则取值长度进行判断
            conditionStr += ` ${item.connectType} cacheObj.${b}.length ${item.condition.state} cacheObj.${d}`
          }
        } else {
          // const b = componentId(6)
          // const d = componentId(6)
          // window.cacheObj[b] = matchModule[item.condition.type]
          // window.cacheObj[d] = item.condition.val
          if (item.condition.type === 'value') {
            conditionStr += ` cacheObj.${b} ${item.condition.state} cacheObj.${d}`
          } else if (item.condition.type === 'valueLength') {
            conditionStr += ` cacheObj.${b}.length ${item.condition.state} cacheObj.${d}`
          }
        }
      })
      let res = false
      // console.log('conditionStr', conditionStr)
      // console.log('cacheObj', window.cacheObj)
      if (!conditionStr) return res
      try {
        // 执行字符串
        res = Function('"use strict";return (' + conditionStr + ')')()
      } catch (error) {
        console.log('error', error)
        res = false
      }
      return res
    },
    /**
     * @description 设置页面模块状态
     * @param type 当前改变的组件的类型：value(值改变) 或 status(状态改变)
     * @param val 改变后的值
     */
    setPageModulesState(type, val) {
      // 编辑模式不运行条件指令
      if (!this.getHasPreview) {
        return
      }
      let modulesStateList = cloneDeep(this.$store.getters['pageModulesState/getPageModulesStates'](this.$store.getters['preview/getNowPageId']))
      modulesStateList.forEach((item) => {
        if (item.id === this.info._id) {
          item[type] = val
        }
      })
      this.$store.dispatch('pageModulesState/setPageModulesStates', {
        pageId: this.$store.getters['preview/getNowPageId'],
        pageState: modulesStateList,
      })
    },
  },
}
